using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery;
using C4F.DevKit.Bluetooth.SerialPortProfile;
using System.Net.Sockets;

namespace SerialPortProfileApplication
{

    public partial class Form1 : Form
    {
        List<Device> devList = null;
        RemoteService serialService = null;
        NetworkStream networkStream = null;
        private byte[] actualDataRead = null;
        private byte[] actualDataWrite = null;
        public Form1()
        {
            InitializeComponent();
            btnProperties.Enabled = false;
            btnConnect.Enabled = false;
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            cmbServices.Enabled = false;
            cmbPortName.Enabled = false;

            devList = deviceServicesManager1.DiscoverAllDevices();
            if (devList.Count != 0)
            {
                foreach (Device dev in devList)
                    cmbDevice.Items.Add(dev.Name);
            }
            if (devList.Count > 0)
            {
                cmbServices.Enabled = true;

            }
        }

        private void btnProperties_Click(object sender, EventArgs e)
        {
                try
                {
                    PortSettings portSettingdForm = new PortSettings(this.sppManager1);
                    portSettingdForm.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to set the properties for port. " 
                        + cmbPortName.Text + "." + ex.Message, "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (sppManager1 != null)
            {
                if (sppManager1.IsPortOpen)
                    sppManager1.ClosePort();
            }
            Dispose();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(cmbPortName.Text) && networkStream != null)
                {

                    sppManager1.NetworkStream = this.networkStream;
                    //open port
                    sppManager1.OpenPort();
                    btnStart.Enabled = false;
                    btnStop.Enabled = true;
                    cmbPortName.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Please enter a valid Port name for e.g. COM1", 
                        "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cmbPortName.Focus();

                }
            }
            catch (Exception ex)
            {
                string errMessage = "";
                if (ex.InnerException != null)
                    errMessage = ex.Message + ex.InnerException.Message;
                else
                    errMessage = ex.Message;
                MessageBox.Show("Unable to start service." + errMessage, "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                cmbPortName.Enabled = true;
            }
        }

        //Data from remote service.
        void serialPortManager_DataDetectedFromRemoteDevice(object sender, EventArgs e)
        {
            try
            {

                byte[] bData;
                int numRead = sppManager1.SendDataToSerialPort(out bData);
                actualDataRead = new byte[numRead];
                Array.Copy(bData, actualDataRead, numRead);
                this.Invoke(new EventHandler(DisplayDataReceivedFromRemoteService));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected error while reading data sent by Remote Service for Legacy Application." + ex.Message,
                   "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //Data from Legacy Application
        void serialPortManager_DataDetectedOnSerialPort(object sender, EventArgs e)
        {
            try
            {
                byte[] bData;
                int numRead = sppManager1.SendDataToRemoteDevice(out bData);
                actualDataWrite = new byte[numRead];
                Array.Copy(bData, actualDataWrite, numRead);
                this.Invoke(new EventHandler(DisplayDataReceivedFromSerialPort));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected error while reading data sent by Legacy application for Remote Service." + ex.Message,
                   "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnDiscover_Click(object sender, EventArgs e)
        {
            cmbDevice.Items.Clear();
            cmbServices.Items.Clear();
            cmbDevice.Text = "";
            cmbServices.Text = "";
            cmbServices.Enabled = false;
            btnConnect.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            devList = deviceServicesManager1.DiscoverAllDevices();
            if (devList.Count != 0)
            {
                foreach (Device dev in devList)
                    cmbDevice.Items.Add(dev.Name);
            }
            if (devList.Count > 0)
            {
                cmbServices.Enabled = true;

            }
            this.Cursor = Cursors.Default;
        }

        private void cmbServices_Enter(object sender, EventArgs e)
        {
            cmbServices.Items.Clear();
            if (devList != null && devList.Count != 0)
            {
                foreach (Device dev in devList)
                {
                    if (dev.Name == cmbDevice.Text.ToString())
                    {
                        List<RemoteService> serialServiceList =
                            deviceServicesManager1.DiscoverServicesByType(dev, ServiceType.SerialPortProfile);
                        if (serialServiceList != null && serialServiceList.Count != 0)
                        {
                            foreach (RemoteService remServ in serialServiceList)
                            {
                                serialService = remServ;
                                cmbServices.Items.Add(remServ.Name);
                            }
                        }
                    }
                }
            }
            if (cmbServices.Items.Count > 0)
                btnConnect.Enabled = true;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try

            {
                this.Cursor = Cursors.WaitCursor;
                if (serialService != null)
                {
                    networkStream = serialService.Connect();
                    btnConnect.Enabled = false;
                    cmbServices.Enabled = false;
                    btnProperties.Enabled = true;
                    cmbPortName.Enabled = true;
                    btnStart.Enabled = true;
                }
            }
            catch (ServiceConnectionException servEx)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                btnProperties.Enabled = false;
                cmbPortName.Enabled = false;
                btnStart.Enabled = false;
                MessageBox.Show(servEx.Message, "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (sppManager1.IsPortOpen)
                    sppManager1.ClosePort();
                btnStop.Enabled = false;
                btnStart.Enabled = true;
                cmbDevice.Enabled = true;
                cmbPortName.Enabled = true;
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                    MessageBox.Show(ex.Message, "Serial Port Application",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(ex.Message + ex.InnerException.Message,
                        "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        //data from normal service
        public void DisplayDataReceivedFromSerialPort(object sender, EventArgs e)
        {
            if (actualDataWrite != null)
            {
                txtBoxLegacyApp.Text += "> " + Encoding.ASCII.GetString(actualDataWrite).Trim() + Environment.NewLine;
                actualDataWrite = null;
            }
        }
        //data from remote service
        public void DisplayDataReceivedFromRemoteService(object sender, EventArgs e)
        {
            if (actualDataRead != null)
            {
                txtBoxRemoteServ.Text += "> " + Encoding.ASCII.GetString(actualDataRead).Trim() + Environment.NewLine;
                actualDataRead = null;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
            foreach (string port in portNames)
            {
                if (!cmbPortName.Items.Contains(port))
                    cmbPortName.Items.Add(port);
            }
        }

        private void cmbPortName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmbPortName.Text))
                btnProperties.Enabled = false;
            else
                btnProperties.Enabled = true;
            try
            {
                sppManager1.PortName = cmbPortName.Text;
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                    MessageBox.Show(ex.Message, "Serial Port Application",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(ex.Message + ex.InnerException.Message,
                        "Serial Port Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }
    }
}